﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.Security.Cryptography;
using Microsoft.SharePoint.Administration;
using System.Security;

namespace IronSharePoint
{
    public class IronScriptSigner
    {
        public static string SignScript(string script)
        {
            if (!SPFarm.Local.CurrentUserIsAdministrator())
                throw new SecurityException("Not allowed!");

            string signing = null;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                RSACryptoServiceProvider rsaAlg = null;
                try
                {
                    string dataToSign = script;

                    CspParameters parameters = new CspParameters();
                    parameters.Flags = CspProviderFlags.UseMachineKeyStore;
                    rsaAlg = new RSACryptoServiceProvider(parameters);
                    rsaAlg.PersistKeyInCsp = false;
                    rsaAlg.ImportCspBlob(IronSettings.Current.PrivateKey);
                    SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider();
                    byte[] binSig = rsaAlg.SignData(Encoding.UTF8.GetBytes(dataToSign), sha);
                    signing = Convert.ToBase64String(binSig);

                }
                finally
                {
                    if (rsaAlg != null)
                        rsaAlg.Clear();
                }
            });

            return signing;
        }

        public static bool VerifyScriptSigning(string script, string signing)
        {
            bool signingValid = false;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                RSACryptoServiceProvider rsaAlg = null;
                try
                {
                    string dataToVerify = script;

                    CspParameters parameters = new CspParameters();
                    parameters.Flags = CspProviderFlags.UseMachineKeyStore;

                    rsaAlg = new RSACryptoServiceProvider(parameters);
                    rsaAlg.PersistKeyInCsp = false;
                    rsaAlg.ImportCspBlob(IronSettings.Current.PrivateKey);
                    SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider();

                    signingValid = rsaAlg.VerifyData(Encoding.UTF8.GetBytes(dataToVerify), sha, Convert.FromBase64String(signing));

                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    if (rsaAlg != null)
                        rsaAlg.Clear();
                }
            });

            return signingValid;
        }
    }
}
